/**
 * @description Sogou Cloud Pinyin Extension for Chrome (Chromium) 
 * @author ZHANG Bei(A.K.A Shinjikun(toaru...)), 
 * iTechs Laboratory, ISCAS, China
 * 
 * <a href="http://www.opensource.org/licenses/gpl-2.0.php">GPLv2</a> Licensed
 */
 
function init() {
	function setState() {
		var element = document.createElement('script');
		element.innerHTML = (localStorage['enabled'] == 'open'
				? 'sogouOpenPinyin();'
				: 'sogouClosePinyin();');
		element.type = 'text/javascript';
		document.getElementsByTagName('head')[0].appendChild(element);
	}

	window.addEventListener('sogouClose', function() {
				chrome.extension.sendRequest({
							type : 'close'
						}, function(response) {
						});
			}, false);

	chrome.extension.onRequest.addListener(function(request, sender,
					sendResponse) {
				try {
					if (request.type) {
						localStorage['enabled'] = request.type;
						setState();
						sendResponse.result = 'ok';
					} else {
						sendResponse.result = 'error';
						sendResponse.error = 'unknow';
					}
				} catch (e) {
					console.dir(e);
					sendResponse.result = 'error';
					sendResponse.error = e;
				}
			}, false);
	{
		var element = document.createElement('script');
		element.src = chrome.extension.getURL("checkState.js");
		document.getElementsByTagName('head')[0].appendChild(element);
	}

}
if (typeof(sogouLoaded) == 'undefined') {
	sogouLoaded = true;
	var used = false;
	chrome.extension.sendRequest({
				type : 'current-state'
			}, function(response) {
				localStorage['enabled'] = response.result;
				init();
			});

}
